import pandas as pd
import webbrowser
from pyecharts.charts import Pie, Timeline
from pyecharts import options as opts

# ===== 1. 数据读取与合并 =====
air_file_path = "data/北京空气质量近十年_2015到2025.xlsx"
sheet_names = ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025']
combined_air_data = []

for year in sheet_names:
    df = pd.read_excel(air_file_path, sheet_name=year)
    df['日期'] = pd.to_datetime(df['日期'], errors='coerce')
    df['AQI指数'] = pd.to_numeric(df['AQI指数'], errors='coerce')
    combined_air_data.append(df[['日期', 'AQI指数', '质量等级']])

df_air = pd.concat(combined_air_data, ignore_index=True).dropna()

# ===== 2. 构造每月统计数据 =====
df_air['month'] = df_air['日期'].dt.month
df_agg = df_air.groupby(['month', '质量等级']).size().reset_index(name='count')
df_agg.columns = ['month', 'grade', 'count']

# ===== 3. 创建时间轴 + 饼图 =====
tl = Timeline(init_opts=opts.InitOpts(width="800px", height="500px", page_title="北京空气质量月度分布"))

for month in range(1, 13):
    df_month = df_agg[df_agg['month'] == month]
    pie = (
        Pie()
        .add(
            "",
            [list(z) for z in zip(df_month['grade'], df_month['count'])],
            radius=["35%", "65%"],
            label_opts=opts.LabelOpts(
                formatter="{b}: {c} ({d}%)",
                font_size=12
            )
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                # title=f"{month}月空气质量等级分布",
                pos_top="5px",  # 距离顶部更近，且居中
                pos_left="center",
                title_textstyle_opts=opts.TextStyleOpts(
                    font_size=20,
                    font_weight="bold",
                    color="#333"
                )
            ),
            legend_opts=opts.LegendOpts(
                type_='scroll',
                pos_bottom="50px",  # 图例放置在底部
                orient="horizontal"
            ),
            tooltip_opts=opts.TooltipOpts(trigger="item")
        )
    )
    tl.add(pie, f"{month}月")

# ===== 4. 渲染 HTML =====
output_path = "air_quality_pie_clean.html"
tl.render(output_path)
webbrowser.open(output_path)
